package com.mtnz.njk.controller;


import com.mtnz.njk.Util.DateUtil;
import com.mtnz.njk.Util.MD5;
import com.mtnz.njk.Util.TokenNote;
import com.mtnz.njk.Util.TokenService;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.QiNiuModel;
import com.mtnz.njk.model.UserInfoModel;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import com.mtnz.njk.service.NjkUserService;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;

/**
 * @Auther: 范保林
 * @Date: 2019\6\14 0014 15:07
 * @Description:
 */
@RequestMapping("/njk")
@RestController
public class NjkUserController {

    @Autowired
    NjkUserService njkUserService;

    @Autowired
    TokenService tokenService;


    /**
     * @api {post} /njk/userLogin 农极客用户登录
     * @apiGrop njkUserLogin
     * @apiParam {String} username 用户名.
     * @apiParam {String} password 用户密码.
     */
    @PostMapping("/userLogin")
    public ResponseResult njkUserLogin(String phone, String password, String phoneType) {
        if (phone == null || phone.equals("") || password == null || password.equals("")) {
            return new ResponseResult<>(ResponseMessage.NULL_REQUEST);
        }
        try { //  手机号是否存在
            NjkUserEntity njkUser = njkUserService.checkUser(phone);
            if (njkUser == null) {
                return new ResponseResult<>(ResponseMessage.FAIL, "账号不存在");
            }
            // 密码加密(使用MD5+盐的方式)
            String md5Password = MD5.md5(MD5.md5(password) + njkUser.getSalt());
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(phone, md5Password);
            Subject subject = SecurityUtils.getSubject();

            //登录操作
            subject.login(usernamePasswordToken);
            NjkUserEntity user = (NjkUserEntity) subject.getPrincipal();
            // 更新用户的登录时间和机型
            user.setLastLogin(DateUtil.getTime());
            if (phoneType != null) {
                user.setPhoneType(phoneType);
            }
            // 修改用户信息
            njkUserService.updateLastLogin(user);
            // 重新查询该用户的信息
            NjkUserEntity userEntity = njkUserService.checkUser(phone);
            return new ResponseResult<>(ResponseMessage.OK, userEntity);

        } catch (UnknownAccountException e) {
            return new ResponseResult<>(ResponseMessage.FAIL, "用户名不存在");
        } catch (IncorrectCredentialsException e) {
            return new ResponseResult<>(ResponseMessage.FAIL, "账号或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult<>(ResponseMessage.FAIL, "程序异常");
        }
    }

    /**
     * @api {post} /njk/createToken 为发送验证码创建token
     * @apiGrop createToken
     * @apiParam {String} phone 手机号
     */
    @PostMapping("/createToken")
    public ResponseResult createToken(String phone) throws Exception {
        NjkUserEntity njkUser = new NjkUserEntity();
        njkUser.setPhone(phone);
        String token = tokenService.getToken(njkUser);
        return new ResponseResult<>(ResponseMessage.OK, token);
    }


    /**
     * @api {post} /njk/njkUserAuthCode 农极客用户手机发送验证码并保存
     * @apiGrop njkUserAuthCode
     * @apiParam {String} phone 用户手机号
     */
    @TokenNote
    @PostMapping("/sendAuthCode")
    public synchronized ResponseResult sendAuthCode(String phone, HttpServletRequest request) throws Exception {
        // 生成，发送，保存验证码
        return njkUserService.saveAuthCode(phone, request);
    }

    /**
     * @api {post} /njk/checkAuthCode 验证用户验证码是否正确
     * @apiGrop checkAuthCode
     * @apiParam {String} phone 用户手机号
     * @apiParam {String} authCode 验证码
     */
    @PostMapping("/checkAuthCode")
    public ResponseResult checkAuthCode(@RequestBody AuthCodeEntity authCode) throws Exception {
        if (authCode.getPhone() == null || authCode.getPhone() == "" || authCode.getAuthCode() == null || authCode.getAuthCode() == "") {
            return new ResponseResult<>(ResponseMessage.NULL_REQUEST);
        }
        HashMap<String, Object> result = njkUserService.checkAuthCode(authCode.getPhone(), authCode.getAuthCode());
        if (result.containsKey("ok"))
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.FAIL, result.get("fail"));
    }

    /**
     * @api {post} /njk/register 用户注册信息
     * @apiGrop register
     * @apiParam {String} NjkUserEntity njk用户实体类
     * @apiParam {String} job 职业信息
     */
    @PostMapping("/register")
    public ResponseResult register(String nickName, String password, String phone, String job, String headimgurl, String unionid, String openid) throws Exception {
        if (nickName == null || nickName.equals("") || job == null || job.equals("") || password == null || password.equals("") || phone == null || phone.equals("")) {
            return new ResponseResult<>(ResponseMessage.NULL_REQUEST);
        }
        ResponseResult register = njkUserService.register(nickName, password, phone, job, headimgurl, unionid, openid);
        return register;
    }

    /**
     * @api {post} /njk/wxLogin 微信登录接口
     * @apiGrop wxLogin
     * @apiParam {String} unionId 微信唯一标识
     * @apiParam {String} phoneType 手机机型（可选）
     */
    @PostMapping("/wxLogin")
    public ResponseResult wxLogin(String unionId, String phoneType) throws Exception {
        if (unionId == null || unionId.equals("")) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.wxLogin(unionId, phoneType);
    }

    /**
     * 微信关联已有账号
     *
     * @param phone
     * @param authCode
     * @return
     * @throws Exception
     */
    @PostMapping("/wxRelevanceAccount")
    public ResponseResult wxRelevanceAccount(String phone, String authCode, String headimgurl, String unionid, String openid, String nickname) throws Exception {
        if (phone == null || ("").equals(phone) || authCode == null || authCode.equals("")) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.wxRelevanceAccount(phone, authCode, headimgurl, unionid, openid, nickname);
    }

    /**
     * 判断手机号是否注册
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @PostMapping("/phoneIfRegister")
    public ResponseResult phoneIfRegister(String phone) throws Exception {
        if (phone == null || ("").equals(phone)) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.phoneIfRegister(phone);
    }

    /**
     * 忘记密码
     *
     * @param phone
     * @param password
     * @param authCode
     * @return
     * @throws Exception
     */
    @PostMapping("/forgetPassword")
    public ResponseResult forgetPassword(String phone, String password, String authCode) throws Exception {
        if (phone == null || phone.equals("") || password == null || password.equals("") || authCode == null || authCode.equals("")) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.forgetPassword(phone, password, authCode);
    }

    /**
     * 重置密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     * @throws Exception
     */
    @PostMapping("/resetPassword")
    public ResponseResult resetPassword(String userId, String oldPassword, String newPassword) throws Exception {
        if (userId == null || userId.equals("") || oldPassword == null || oldPassword.equals("") || newPassword == null || newPassword.equals(""))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.resetPassword(userId, oldPassword, newPassword);
    }

    /**
     * 展示用户个人信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/userInfoMessage")
    public ResponseResult userInfoMessage(String userId) throws Exception {
        if (userId == null || ("").equals(userId)) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.userInfoMessage(userId);
    }

    /**
     * 用户修改个人信息
     *
     * @param userInfoModel
     * @return
     * @throws Exception
     */
    @PostMapping("/updateUserInfoMessage")
    public ResponseResult updateUserInfoMessage(@RequestBody UserInfoModel userInfoModel) throws Exception {
        if (userInfoModel == null || userInfoModel.getUserId() == null || ("").equals(userInfoModel.getUserId()))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.updateUserInfoMessage(userInfoModel);
    }

    /**
     * 用户添加收货地址
     *
     * @param addressEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/addUserAddress")
    public ResponseResult addUserAddress(@RequestBody NjkUserAddressEntity addressEntity) throws Exception {
        if (addressEntity == null)
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.addUserAddress(addressEntity);

    }

    /**
     * 用户收货地址列表
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/listUserAddress")
    public ResponseResult listUserAddress(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, String userId) throws Exception {
        if (userId == null || userId == "")
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.listUserAddress(pageNum, pageSize, userId);
    }

    /**
     * 用户修改收货地址
     *
     * @param addressEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/updateUserAddress")
    public ResponseResult updateUserAddress(@RequestBody NjkUserAddressEntity addressEntity) throws Exception {
        return njkUserService.updateUserAddress(addressEntity);
    }

    /**
     * 用户删除收货地址
     *
     * @param addressId
     * @return
     * @throws Exception
     */
    @PostMapping("/delUserAddress")
    public ResponseResult delUserAddress(String addressId) throws Exception {
        if (addressId == null || addressId == "")
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.delUserAddress(addressId);
    }

    /**
     * 用户咨询客服
     *
     * @param userId
     * @param productId
     * @return
     * @throws Exception
     */
    @PostMapping("/consultService")
    public ResponseResult consultService(String userId, String productId) throws Exception {
        if (userId == null || ("").equals(userId) || productId == null || ("").equals(productId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.consultService(userId, productId);
    }

    /**
     * 我的代金券
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/myCoupon")
    public ResponseResult myCoupon(String userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.myCoupon(userId, pageNum, pageSize);
    }

    /**
     * 用户反馈建议
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/userOpinion")
    public ResponseResult userOpinion(String userId, String message, String imgs) throws Exception {
        if (userId == null || userId.equals("") || message == null || message.equals("")) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.userOpinion(userId, message, imgs);
    }

    /**
     * 我的信息首页
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/userIndexPage")
    public ResponseResult userIndexPage(String userId) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.userIndexPage(userId);
    }

    /**
     * 用户签到
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/userSign")
    public ResponseResult userSign(String userId, Integer integral) throws Exception {
        if (userId == null || ("").equals(userId) || integral == null) {
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        }
        return njkUserService.userSign(userId, integral);
    }

    /**
     * 我的订单
     *
     * @param userId
     * @param orderProductId
     * @return
     * @throws Exception
     */
    @PostMapping("/myOrder")
    public ResponseResult myOrder(String orderNumber, String userId, String orderProductId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.myOrder(orderNumber, userId, orderProductId, pageNum, pageSize);
    }

    /**
     * 我的待付款
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @PostMapping("/myWaitPay")
    public ResponseResult myWaitPay(String userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.myWaitPay(userId, pageNum, pageSize);
    }




    /**
     * 删除待支付订单
     *
     * @param orderInfoId
     * @return
     * @throws Exception
     */
    @PostMapping("/delWaitPay")
    public ResponseResult delWaitPay(String orderInfoId, String userId) throws Exception {
        return njkUserService.delWaitPay(orderInfoId, userId);
    }

    /**
     * 我的积分明细
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @PostMapping("/myIntegralDetail")
    public ResponseResult myIntegralDetail(String userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.myIntegralDetail(userId, pageNum, pageSize);
    }

    /**
     * 我的客服
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/myService")
    public ResponseResult myService(String userId) throws Exception {
        if (userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.myService(userId);
    }

    /**
     * 用户修改密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     * @throws Exception
     */
    @PostMapping("/updatePassword")
    public ResponseResult updatePassword(String userId, String oldPassword, String newPassword) throws Exception {
        if (userId == null || ("").equals(userId) || oldPassword == null || ("").equals(oldPassword) || newPassword == null || ("").equals(newPassword))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.updatePassword(userId, oldPassword, newPassword);
    }

    /**
     * 用户充值余额
     *
     * @param orderInfoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/rechargeBalance")
    public ResponseResult rechargeBalance(@RequestBody OrderInfoEntity orderInfoEntity) throws Exception {
        if (orderInfoEntity == null)
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.rechargeBalance(orderInfoEntity);
    }

    /**
     * 账单明细
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/billDetail")
    public ResponseResult billDetail(String userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null)
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.billDetail(userId, pageNum, pageSize);
    }

    /**
     * 余额明细
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/balanceDetail")
    public ResponseResult balanceDetail(String userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        if (userId == null)
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.balanceDetail(userId, pageNum, pageSize);
    }

    /**
     * 插入个推识别用户id——clientId
     *
     * @param clientId
     * @return
     * @throws Exception
     */
    @PostMapping("/insertClient")
    public ResponseResult insertClientId(String userId,String clientId) throws Exception {
        if (clientId == null || ("").equals(clientId) || userId == null || ("").equals(userId))
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        return njkUserService.insertClientId(userId,clientId);
    }

    // 获取 七牛云的 token
    @GetMapping(value = "/getToken")
    public QiNiuModel getToken() {
        QiNiuModel qiNiu = new QiNiuModel();
        String accessKey = "spnYj8X7EINqVRkTNEKfh197BHlQ1MMHhUb15y6i";
        String secretKey = "zIP6bdZFAuuag_7yYB8X0VeUFT8gLhAbRhGqHz2B";
        String bucket = "nongjike";
        long expireSeconds = 600;   //过期时间
        StringMap putPolicy = new StringMap();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        qiNiu.setKey(UUID.randomUUID().toString().replaceAll("\\-", ""));
        qiNiu.setToken(upToken);
        return qiNiu;
    }

}